#!/usr/bin/perl

# Author: Premshree Pillai
# http://premshree.livejournal.com

use LWP::Simple;
use XML::Simple;
use Data::Dumper;
use File::Path;

$searchword = $ARGV[0];

my $url = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=asdfasdfasd&query=$searchword&results=50&format=jpeg";
my $url2 = "http://search.yahooapis.com/ImageSearchService/V1/imageSearch?appid=asdfasdfasd&query=$searchword&results=50&format=jpeg&start=58";

# make the request
my $results = get $url || die "Web services request failed: $!";
my $results2 = get $url2 || die "Web services request failed: $!";
my $ref = XMLin($results);
my $ref2 = XMLin($results2);

my $time = "tmp/" . time();
mkpath($time,0);
mkpath($time . "/prep",0);
getstore( $ref->{Result}->[0]->{ClickUrl}, $time . "/mainimage.jpg" );
my $mainimage = $ref->{Result}->[0]->{ClickUrl};
print getstore( $ref->{Result}->[$count]->{Thumbnail}->{Url}, $time . "/image" . $count . ".jpg" );

open(TMP,"> /mnt/tc/wrk_school/al_building/$searchword.html");

my $output = qq!
<img src="./$searchword.png">
<BR>
<A href="$mainimage">$mainimage</A>
!;

print TMP $output;
close(TMP);


my $flag = 1;
while ($flag) {
    if ( $ref->{Result}->[$count]->{Thumbnail}->{Url} ) {
        print $ref->{Result}->[$count]->{Thumbnail}->{Url} . "\n" ;
        print getstore( $ref->{Result}->[$count]->{Thumbnail}->{Url}, $time . "/image" . $count . ".jpg" );
    }
    else {
        $flag = 0;
    }
    $count++;
}
$flag = 1;
my $count2 = 0;
while ($flag) {
print "------------------------\n";
    if ( $ref2->{Result}->[$count2]->{Thumbnail}->{Url} ) {
        print $ref2->{Result}->[$count2]->{Thumbnail}->{Url} . "\n" ;
        print getstore( $ref2->{Result}->[$count2]->{Thumbnail}->{Url}, $time . "/image" . $count . ".jpg" );
    }
    else {
        $flag = 0;
    }
    $count++;
    $count2++;
}



system("metapixel-prepare --width=32 --height=32 ./$time ./$time/prep");
system("metapixel -w 32 -h 32 -d 1 -a 40 --metapixel  ./$time/mainimage.jpg /mnt/tc/wrk_school/al_building/$searchword.png --library ./$time/prep");
